package org.rcy.framework.data.config.mybatis.plugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.rcy.framework.api.entity.IdEntity;
import org.rcy.framework.data.id.LongIdGenerator;

import java.util.Properties;

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class,Object.class }) })
public class InsertIdGeneratePlugin implements Interceptor{

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object[] args = invocation.getArgs();
		if (args == null || args.length != 2 || !(args[0] instanceof MappedStatement)) {
			return invocation.proceed();
		}
		MappedStatement mappedStatement = (MappedStatement) args[0];
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		if (!SqlCommandType.INSERT.equals(sqlCommandType)) {
			return invocation.proceed();
		}
		setDefultProperty(args[1]);
		return invocation.proceed();
	}
	
	public void setDefultProperty(Object obj) {
		if(obj instanceof IdEntity) {
			IdEntity idEntity = (IdEntity)obj;
			if(idEntity.getId() == null) {
				Long generate = LongIdGenerator.generate();
				idEntity.setId(generate);
			}
		}
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}
